<template>
  <BasicDrawer v-bind="$attrs" @register="registerModal" showFooter @ok="handleSubmit">
    <BasicTree treeWrapperClassName="h-[calc(100%-35px)] overflow-auto" ref="treeRef" title="菜单授权" search checkable
      checkStrictly :defaultExpandAll="true" :treeData="treeData" :fieldNames="{ key: 'id', title: 'title' }"
      :value="mid" />
  </BasicDrawer>
</template>
<script lang="ts">
import { defineComponent, onMounted, ref, unref } from 'vue';
import { BasicTree, TreeActionType } from '/@/components/Tree';
import { getViewPremTree } from '/@/api/system/view';
import { setAdminView } from '/@/api/system/admin';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';

export default defineComponent({
  name: 'SetViewDrawer',
  components: { BasicDrawer, BasicTree },
  emits: ['success', 'register'],
  setup(_, { emit }) {
    const treeRef = ref<Nullable<TreeActionType>>(null);
    const treeData = ref<any[]>([]);
    const oid = ref(0);
    const mid = ref([]);

    async function fetch() {
      treeData.value = (await getViewPremTree()) as any;
    }
    onMounted(() => {
      fetch();
    })

    function getTree() {
      const tree = unref(treeRef);
      if (!tree) {
        throw new Error('tree is null!');
      }
      return tree;
    }
    const [registerModal, { setDrawerProps, closeDrawer }] = useDrawerInner(async ({ record }) => {
      setDrawerProps({ confirmLoading: false });
      oid.value = record.id;
      mid.value = record.views;
    });

    async function handleSubmit() {
      try {
        setDrawerProps({ confirmLoading: true });
        const keys = getTree().getCheckedKeys() as any;
        await setAdminView({ oid: oid.value, mid: keys.checked });
        closeDrawer();
        emit('success');
      } finally {
        setDrawerProps({ confirmLoading: false });
      }
    }
    return { treeRef, treeData, mid, registerModal, handleSubmit };
  }
})
</script>
